<template>
  <div class="btn-item" @click="open">
    <svg-icon name="icon-emoji" color="#fff"></svg-icon>
    <div class="dialog" :class="{ act: showDialog }" @click.stop>
      <div class="item" v-for="item in emoji" :key="item" @click.stop="onSelect(item)">
        {{ item }}
      </div>
    </div>
  </div>
</template>

<script setup>
import emoji from '../../../../constants/emoji'
import { ref } from 'vue';

const showDialog = ref(false)

// 打开对话框并绑定事件
function open() {
  
  showDialog.value = !showDialog.value;

 
  if (showDialog.value) {
    // 使用 setTimeout 确保对话框已经显示后再添加事件监听器
    setTimeout(() => {
      document.body.addEventListener('click', closeDialog, { once: true });
    }, 0);
  }
}

// 关闭对话框
function closeDialog(event) {
  // 防止点击对话框区域时关闭
  if (event.target.closest('.btn-item')) {
    return;
  }
  

  showDialog.value = false;
}

// 选择emoji
function onSelect(item) {

emit('onChange', item)  // 触发父组件的 onChange 事件
}

// 通过 defineEmits 来声明事件
const emit = defineEmits(['onChange'])
</script>

<style scoped lang="scss">
.btn-item {
  width: 50px;
  height: 50px; 
  background-color: rgba(255, 255, 255, 0.25);
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 26px;
  position: relative;
  cursor: pointer;
  &:hover {
    background-color: rgba(255, 255, 255, 0.2);
  }
}

.dialog {
  width: 300px;
  background: #222222;
  position: absolute;
  bottom: 70px;
  left: 0;
  border-radius: 10px;
  display: flex;
  justify-content: flex-start;
  align-items: flex-start;
  flex-wrap: wrap;
  overflow-y: auto;
  overflow-x: hidden;
  height: 0;
  transition: height 0.3s ease; /* 确保动画顺畅 */
  cursor: pointer;
  
  .item {
    width: 36px;
    height: 36px;
    display: flex;
    justify-content: center;
    align-items: center;
    color: white;
  }

  &.act {
    height: 360px; /* 显示时的高度 */
  }
}
</style>
